package gz.itcast.c_prepared;

import gz.itcast.util.JdbcUtil;
import org.junit.Test;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;

/**
 * Created 吴海杰 on 2017/2/27.
 */
public class Demo2 {
    private String name1="rose";
    private String password1="654321";
    @Test
    public void testByStatement() {
        Connection conn = null;
        Statement stmt = null;
        ResultSet rs=null;
        try {
            conn = JdbcUtil.getConnection();
            String sql = "  SELECT *FROM users WHERE name='"+name1+"' AND password='"+password1+"'; ";
            stmt=conn.createStatement();
            rs = stmt.executeQuery(sql);
           if (rs.next()){
                System.out.println("登陆成功");
            }else {
               System.out.println("登录失败");
           }
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        } finally {
            JdbcUtil.close(conn, stmt);
        }
    }


    @Test
    public void testByPreparedStatement() {
        Connection conn = null;
        PreparedStatement stmt = null;
        ResultSet rs=null;
        try {
            conn = JdbcUtil.getConnection();
            String sql = "SELECT *FROM users WHERE name =?   AND password=? ;";
            //预编译
            stmt=conn.prepareStatement(sql);
            stmt.setString(1,name1);
            stmt.setString(2,password1);
            rs = stmt.executeQuery();
            if (rs.next()){
                System.out.println("登陆成功");
            }else {
                System.out.println("登录失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        } finally {
            JdbcUtil.close(conn, stmt);
        }
    }

}
